# -*- coding: utf-8 -*-
from datetime import datetime
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
import re
import logging
from django.contrib.sitemaps import Sitemap
logger = logging.getLogger(__name__)

try: 
    from tinymce import models as tinymce_models
except ImportError, e:
    logger.debug('tiny mce not found')
    

from apps.blog.managers import *

class Category(models.Model):
    name = models.CharField(_('name'), max_length=255)
    slug = models.SlugField(_('slug'), max_length=255, unique=True)
    creation_date = models.DateTimeField(_('creation date'), auto_now_add=True)
    modification_date = models.DateTimeField(_('modification date'), auto_now=True)
    icon = models.ImageField(upload_to='categories', max_length=255, null = True, blank = True)
    objects = models.Manager()
    online_objects = CategoryOnlineManager()
    
    class Meta:
        verbose_name = _('category')
        verbose_name_plural = _('categories')
        
    def __unicode__(self):
        return u'%s' % self.name

    @models.permalink
    def get_absolute_url(self):
        return ('Category_Detail', (), {
            'slug': str(self.slug),
        })

    def _get_online_entries(self):
        """
        Returns entries in this category with status of "online".
        Access this through the property ``online_entry_set``.
        """
        return self.entry_set.filter(status=Entry.STATUS_ONLINE)

    online_entry_set = property(_get_online_entries)


class Entry(models.Model):
    STATUS_OFFLINE = 0
    STATUS_ONLINE = 1
    STATUS_DEFAULT = STATUS_OFFLINE
    STATUS_CHOICES = (
        (STATUS_OFFLINE, _('Offline')),
        (STATUS_ONLINE, _('Online')),
    )

    title = models.CharField(_('title'), max_length=255)
    slug = models.SlugField(_('slug'), max_length=255, unique_for_date='publication_date')
    author = models.ForeignKey('auth.User', verbose_name=_('author'))
    category = models.ForeignKey(Category, verbose_name=_('category'))
    creation_date = models.DateTimeField(_('creation date'), auto_now_add=True)
    modification_date = models.DateTimeField(_('modification date'), auto_now=True)
    publication_date = models.DateTimeField(_('publication date'), default=datetime.now(), db_index=True)
    status = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=STATUS_DEFAULT, db_index=True)
    header = models.TextField(_('header'))
    body = models.TextField(_('body'))
    
    tags = models.CharField(max_length=200)
    #posts = [post for post in Post.objects.all() if 'tag' in post.get_tag_list()]  
    def get_tag_list(self):
        return re.split(", ", self.tags)
    
    if 'tinymce' in settings.INSTALLED_APPS:
        body = tinymce_models.HTMLField(_('body'))
        header = tinymce_models.HTMLField(_('header'))
   
    objects = models.Manager()
    online_objects = EntryOnlineManager()

    class Meta:
        verbose_name = _('entry')
        verbose_name_plural = _('entries')

    def __unicode__(self):
        return u'%s' % self.title

    @models.permalink
    def get_absolute_url(self):
        return ('Entry_Detail', (), {
            'year': (self.publication_date.strftime('%Y')),
            'month': (self.publication_date.strftime('%m')),
            'day': (self.publication_date.strftime('%d')),
            'slug': str(self.slug),
        })
        
        
class CategoriesSitemap(Sitemap):
    changefreq = "never"
    priority = 0.5

    def items(self):
        return Category.objects.all()

    def lastmod(self, obj):
        return obj.creation_date
    
class BlogSitemap(Sitemap):
    changefreq = "never"
    priority = 0.5

    def items(self):
        return Entry.online_objects.all()

    def lastmod(self, obj):
        return obj.creation_date